<template>
	<view class="container">
		<view class="tech-header">
			<view class="header-bg">
				<view class="tech-lines"></view>
				<view class="tech-dots"></view>
			</view>
			<text class="header-title">物品入库</text>
			<text class="header-subtitle">INVENTORY MANAGEMENT SYSTEM</text>
		</view>

		<view class="tech-card">
			<view class="card-header">
				<view class="card-icon">
					<uni-icons type="plus" size="24" color="#fff"></uni-icons>
				</view>
				<text class="card-title">物品信息录入</text>
				<view class="card-line"></view>
			</view>

			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" label-position="top">
				<!-- 修改物品编号输入框部分 -->
				<uni-forms-item label-width="180rpx" label="物品编号" required name="goods_id">
					<view class="input-with-scan">
						<uni-easyinput v-model="valiFormData.goods_id" placeholder="请输入物品唯一编号" />
						<button class="scan-button" @click="scanQRCode">
							<uni-icons type="scan" size="24" color="#3498db"></uni-icons>
						</button>
						<button class="generate-button" @click="generateBarcode">
							<uni-icons type="loop" size="24" color="#3498db"></uni-icons>
						</button>
					</view>
				</uni-forms-item>

				<uni-forms-item label-width="180rpx" label="分类" required name="category_id">
					<uni-data-select class="select" :arrayConfig="configParams" v-model="value" @change="change"
						:localdata="categoriesData" placeholder="请选择分类">
					</uni-data-select>
				</uni-forms-item>

				<uni-forms-item label-width="180rpx" label="物品图片" name="thumb">
					<view class="upload-section">
						<uni-file-picker v-model="imageFiles" @select="onImageSelect" @delete="onImageDelete"
							file-mediatype="image" limit="1" mode="grid" showType="grid" :image-styles="imageStyles"
							:auto-upload="false">
							<view class="upload-area">
								<uni-icons v-if="!imageFiles || imageFiles.length === 0" type="camera" size="36"
									color="#3498db"></uni-icons>
								<text v-if="!imageFiles || imageFiles.length === 0" class="upload-text">点击上传图片</text>
							</view>
						</uni-file-picker>
						<text v-if="uploading" class="upload-status">图片上传中...</text>
					</view>
				</uni-forms-item>

				<uni-forms-item label-width="180rpx" label="名称" required name="name">
					<uni-easyinput v-model="valiFormData.name" placeholder="请输入物品名称" />
				</uni-forms-item>

				<uni-forms-item label-width="180rpx" label="描述" name="desc">
					<uni-easyinput v-model="valiFormData.desc" placeholder="请输入物品描述" />
				</uni-forms-item>

				<view class="form-row">
					<uni-forms-item label-width="180rpx" label="品牌" name="brand">
						<uni-easyinput v-model="valiFormData.brand" placeholder="请输入物品品牌" />
					</uni-forms-item>

					<uni-forms-item label-width="180rpx" label="型号" name="model">
						<uni-easyinput v-model="valiFormData.model" placeholder="请输入物品型号" />
					</uni-forms-item>
				</view>

				<uni-forms-item label-width="180rpx" label="库存" required name="remain_count">
					<uni-easyinput v-model="valiFormData.remain_count" placeholder="请输入库存数量" type="digit" />
				</uni-forms-item>

				<uni-forms-item label-width="180rpx" label="备注" name="note">
					<uni-easyinput v-model="valiFormData.note" placeholder="请输入备注信息" />
				</uni-forms-item>
			</uni-forms>

			<view class="action-buttons">
				<button class="submit-btn" @click="submit('valiForm')">提交入库</button>
				<button class="reset-btn" @click="resetForm">重置表单</button>
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				uploading: false,
				configParams: {
					labelKey: "name",
					valueKey: "_id",
				},
				categoriesData: [],
				value: null,
				imageFiles: [],
				imageStyles: {
					height: 120,
					width: 120,
					border: {
						color: "#3498db",
						width: 1,
						style: "dashed"
					}
				},
				valiFormData: {
					goods_id: '',
					category_id: null,
					name: '',
					brand: null,
					model: null,
					remain_count: null,
					desc: '',
					thumb: null,
					is_on_sale: true,
					add_date: null,
					last_modify_date: null,
					note: '',
					status: 0
				},
				rules: {
					goods_id: {
						rules: [{
							required: true,
							errorMessage: '物品编号不能为空'
						}]
					},
					category_id: {
						rules: [{
							required: true,
							errorMessage: '请选择分类'
						}]
					},
					name: {
						rules: [{
							required: true,
							errorMessage: '名称不能为空'
						}]
					},
					remain_count: {
						rules: [{
								required: true,
								errorMessage: '库存不能为空'
							},
							{
								format: 'number',
								errorMessage: '只能输入数字'
							}
						]
					}
				},
			}
		},
		mounted() {
			this.getCategoriesList()
		},
		methods: {
			// 获取分类列表
			async getCategoriesList() {
				try {
					const obj = uniCloud.importObject('goods')
					const res = await obj.getCategoriesList({})
					this.categoriesData = res.data.map(item => ({
						value: item._id,
						text: item.name
					}));
				} catch (e) {
					uni.showToast({
						title: '分类加载失败',
						icon: 'none'
					})
				}
			},
			change(e) {
				if (e && e.value) {
					this.value = e.value
					this.valiFormData.category_id = e.value
				} else {
					this.value = null
					this.valiFormData.category_id = null
				}
			},

			onImageSelect(e) {
				this.imageFiles = e.tempFiles;
			},

			onImageDelete(e) {
				this.imageFiles = [];
				this.valiFormData.thumb = null;
			},

			generateCloudPath(originalName) {
				const ext = originalName.split('.').pop()
				const timestamp = Date.now()
				const category_id = this.valiFormData.category_id || 'default'
				return `goods/${category_id}/${timestamp}.${ext}`
			},

			// 上传图片到云存储
			async uploadFile(file) {
				const cloudPath = this.generateCloudPath(file.name)
				return uniCloud.uploadFile({
					filePath: file.path || file.url,
					cloudPath,
					cloudPathAsRealPath: true
				})
			},

			async submit(ref) {
				try {
					await this.$refs[ref].validate();

					if (!this.valiFormData.category_id) {
						uni.showToast({
							title: '请选择物品分类',
							icon: 'none'
						});
						return;
					}

					if (!this.imageFiles || this.imageFiles.length === 0) {
						uni.showToast({
							title: '请上传物品图片',
							icon: 'none'
						});
						return;
					}

					const file = this.imageFiles[0];
					const res = await this.uploadFile(file);
					this.valiFormData.thumb = res.fileID;

					const now = Date.now();
					this.valiFormData.add_date = now;
					this.valiFormData.last_modify_date = now;
					this.valiFormData.remain_count = Number(this.valiFormData.remain_count);
					
					// 获取当前用户信息
					const userInfo = uni.getStorageSync('userInfo');
					this.valiFormData.operator = userInfo._id || 'system';
					this.valiFormData.operator_name = userInfo.username || userInfo.name || 'system';

					// 调用云函数
					const obj = uniCloud.importObject('goods')
					const result = await obj.addGoods(this.valiFormData)

					if (result.code === 0) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						this.resetForm()
					} else if (result.code === 409) { // 处理重复添加的情况
						uni.showToast({
							title: result.message,
							icon: 'none'
						});
					} else {
						throw new Error(result.message || '提交失败');
					}

					uni.showToast({
						title: '物品入库成功',
						icon: 'success'
					});

					this.resetForm();

				} catch (err) {
					console.error('提交错误:', err);
					uni.showToast({
						title: '请检查表单填写',
						icon: 'none'
					});
				}
			},

			resetForm() {
				this.valiFormData = {
					goods_id: null,
					category_id: null,
					name: '',
					brand: null,
					model: null,
					remain_count: null,
					desc: '',
					thumb: null,
					is_on_sale: true,
					add_date: null,
					last_modify_date: null,
					note: '',
					status: 0
				};
				this.value = null;
				this.imageFiles = [];
				this.$refs.valiForm.clearValidate();
			},
			//扫码添加物品
			async scanQRCode() {
				uni.scanCode({
					success: async (res) => {
						let barcode = res.result.trim();
						if (!/^\d+$/.test(barcode)) {
							uni.showToast({
								title: "无效的条形码",
								icon: "none"
							});
							return;
						}

						uni.showLoading({
							title: "查询中..."
						});

						try {
							const obj = uniCloud.importObject('basedata');
							const result = await obj.queryBarcode({
								barcode
							});

							if (result.code != 0) {
								uni.showToast({
									title: result.message,
									icon: 'none'
								});
								return;
							}

							// 检查是否已存在该物品
							const goodsObj = uniCloud.importObject('goods');
							const existsRes = await goodsObj.checkGoodsExists({
								goods_id: barcode
							});

							if (existsRes.exists) {
								uni.showToast({
									title: '该物品已存在',
									icon: 'none'
								});
								return;
							}
							uni.showToast({
								title: "扫码成功",
								icon: "success"
							});

							// 填充表单数据
							const data = result.data;
							this.valiFormData.goods_id = data.barcode;
							this.valiFormData.name = data.name;
							this.valiFormData.brand = data.brand;
							this.valiFormData.model = data.type;
							this.valiFormData.desc = data.description;

						} catch (e) {
							uni.showToast({
								title: '查询失败',
								icon: 'none'
							});
						} finally {
							uni.hideLoading();
						}
					},
					fail: () => {
						uni.showToast({
							title: "扫码失败",
							icon: "none"
						});
					}
				});
			},

			// 生成随机条形码
			generateBarcode() {
				// 生成12位随机数字（符合EAN-13标准的前12位）
				let barcode = '';
				for (let i = 0; i < 12; i++) {
					barcode += Math.floor(Math.random() * 10);
				}

				// 计算校验位
				let sum = 0;
				for (let i = 0; i < 12; i++) {
					const digit = parseInt(barcode[i]);
					if (i % 2 === 0) {
						sum += digit; // 奇数位置
					} else {
						sum += digit * 3; // 偶数位置乘以3
					}
				}
				const checkDigit = (10 - (sum % 10)) % 10;
				barcode += checkDigit;

				this.valiFormData.goods_id = barcode;
				uni.showToast({
					title: "条形码已生成",
					icon: "success"
				});
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: linear-gradient(135deg, #f0f8ff 0%, #e6f7ff 100%);
		padding: 20rpx;
		font-family: 'Helvetica Neue', Arial, sans-serif;
	}

	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.tech-header {
		position: relative;
		padding: 40rpx 0;
		text-align: center;
		margin-bottom: 30rpx;
		overflow: hidden;
		border-radius: 20rpx;
		background: linear-gradient(135deg, #3498db 0%, #1a5f9e 100%);
		box-shadow: 0 10rpx 30rpx rgba(52, 152, 219, 0.3);

		.header-bg {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			overflow: hidden;
		}

		.tech-lines {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background:
				linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px),
				linear-gradient(0deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
			background-size: 40rpx 40rpx;
			opacity: 0.5;
		}

		.tech-dots {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 2rpx, transparent 2rpx);
			background-size: 30rpx 30rpx;
		}

		.header-title {
			font-size: 42rpx;
			font-weight: bold;
			color: #fff;
			text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
			position: relative;
			z-index: 2;
			letter-spacing: 2rpx;
		}

		.header-subtitle {
			display: block;
			font-size: 24rpx;
			color: rgba(255, 255, 255, 0.8);
			margin-top: 10rpx;
			letter-spacing: 4rpx;
			position: relative;
			z-index: 2;
		}
	}

	.tech-card {
		background: #fff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 10rpx 40rpx rgba(52, 152, 219, 0.15);
		margin-bottom: 40rpx;
		flex: 1;

		.card-header {
			display: flex;
			align-items: center;
			margin-bottom: 40rpx;
			position: relative;

			.card-icon {
				width: 60rpx;
				height: 60rpx;
				background: linear-gradient(135deg, #3498db 0%, #1a5f9e 100%);
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 5rpx 15rpx rgba(52, 152, 219, 0.3);
			}

			.card-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #2c3e50;
				margin-left: 20rpx;
			}

			.card-line {
				position: absolute;
				bottom: -15rpx;
				left: 0;
				width: 120rpx;
				height: 6rpx;
				background: linear-gradient(90deg, #3498db, #1a5f9e);
				border-radius: 3rpx;
			}
		}
	}

	.upload-section {
		margin-top: 20rpx;

		.upload-area {
			width: 100%;
			height: 200rpx;
			border: 2rpx dashed #3498db;
			border-radius: 16rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			background-color: #f8fbff;
			transition: all 0.3s;

			&:active {
				background-color: #e6f2ff;
			}
		}

		.upload-text {
			font-size: 28rpx;
			color: #3498db;
			margin-top: 20rpx;
		}

		.upload-status {
			display: block;
			font-size: 26rpx;
			color: #3498db;
			text-align: center;
			margin-top: 20rpx;
		}
	}

	.form-row {
		display: flex;
		flex-wrap: wrap;
		margin: 0 -20rpx;

		.uni-forms-item {
			flex: 1 0 50%;
			padding: 0 20rpx;
			box-sizing: border-box;
			min-width: 300rpx;
		}
	}

	.action-buttons {
		display: flex;
		margin-top: 60rpx;
		gap: 30rpx;

		button {
			flex: 1;
			height: 90rpx;
			border-radius: 12rpx;
			font-size: 32rpx;
			font-weight: 500;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s;
			box-shadow: 0 6rpx 20rpx rgba(52, 152, 219, 0.25);

			&::after {
				border: none;
			}
		}

		.submit-btn {
			background: linear-gradient(135deg, #3498db 0%, #1a5f9e 100%);
			color: white;

			&:active {
				transform: translateY(4rpx);
				box-shadow: 0 2rpx 10rpx rgba(52, 152, 219, 0.3);
			}
		}

		.reset-btn {
			background: #fff;
			color: #3498db;
			border: 2rpx solid #3498db;

			&:active {
				transform: translateY(4rpx);
				box-shadow: 0 2rpx 10rpx rgba(52, 152, 219, 0.2);
			}
		}
	}

	/* 表单元素样式调整 */
	.uni-forms-item__label {
		font-weight: bold;
		color: #2c3e50;
	}

	.uni-easyinput {
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		overflow: hidden;
		transition: all 0.3s;

		&:focus-within {
			border-color: #3498db;
			box-shadow: 0 0 10rpx rgba(52, 152, 219, 0.2);
		}
	}

	.uni-data-select {
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		height: 80rpx;
		padding: 0 20rpx;

		&__input {
			height: 100%;
		}
	}

	/* 新增扫码按钮样式 */
	.input-with-scan {
		display: flex;
		align-items: center;

		.uni-easyinput {
			flex: 1;
			margin-right: 20rpx;
		}

		.scan-button,
		.generate-button {
			width: 80rpx;
			height: 80rpx;
			border-radius: 12rpx;
			background-color: #f0f8ff;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 1rpx solid #3498db;
			padding: 0;
			margin-left: 10rpx;

			&::after {
				border: none;
			}

			&:active {
				background-color: #e6f2ff;
				transform: scale(0.95);
			}
		}
	}
</style>